package com.tuniu.agents.advisor;

import com.google.common.base.Strings;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.messages.Message;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * Agent LLM chat record storage Redis implementation
 */
public class RedisChatMemory implements ChatMemory {

    private static final String REDIS_MEMORY_KEY_PREFIX = "ChatMemory:";

    private static final int DEFAULT_EXPIRATION_DAYS = 7;

    private final RedisTemplate<String, Message> redisTemplate;

    public RedisChatMemory(RedisTemplate<String, Message> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Override
    public void add(String conversationId, List<Message> messages) {
        String key = key(conversationId);
        // Store messages in Redis
        this.redisTemplate.opsForList().rightPushAll(key, messages);
        this.redisTemplate.expire(key, DEFAULT_EXPIRATION_DAYS, TimeUnit.DAYS);
    }

    @Override
    public List<Message> get(String conversationId, int lastN) {
        String key = key(conversationId);
        // Get the latest lastN messages from Redis
        List<Message> serializedMessages = redisTemplate.opsForList().range(key, -lastN, -1);
        if (serializedMessages != null) {
            return serializedMessages;
        }
        return List.of();
    }

    @Override
    public void clear(String conversationId) {
        // Delete the conversation from Redis
        this.redisTemplate.delete(conversationId);
    }

    public String key(String conversationId) {
        if (Strings.isNullOrEmpty(conversationId)) {
            return null;
        }
        return REDIS_MEMORY_KEY_PREFIX + conversationId;
    }
}